package com.wash.car.web.controller.applets;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.core.util.IdUtil;
import com.pmo.boot.common.api.DefaultResult;
import com.wash.car.biz.UserServer;
import com.wash.car.dao.domain.CarUserDomain;
import com.wash.car.dao.model.UserAddModel;
import com.wash.car.web.config.CacheConfiguration;
import com.wash.car.web.config.WxMaConfiguration;
import com.wash.car.web.config.context.UserInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@Api(tags = {"登录管理"})
@RestController
@RequestMapping(path = "/applets")
public class AppletsLogInController {

    @Autowired
    private UserServer userServer;


    @ApiOperation(value = "登录")
    @PostMapping(path = "login")
    public DefaultResult<AppletsLoginReturnModel> login(@RequestBody AppletsLoginModel model) throws WxErrorException {
        WxMaService wxMaService = WxMaConfiguration.getMaService(model.getAppid());
        WxMaJscode2SessionResult wxMaJscode2SessionResult = wxMaService.jsCode2SessionInfo(model.getJsCode());
        log.info("获取登录后的session信息,结果：{}", wxMaJscode2SessionResult);
        String openid = wxMaJscode2SessionResult.getOpenid();
        CarUserDomain carUserDomain = userServer.wxRegister(new UserAddModel().setOpenid(openid));
        String token = IdUtil.fastSimpleUUID();
        CacheConfiguration.add(token, new UserInfo().setToken(token).setOpenid(openid).setUserId(carUserDomain.getId()));
        return DefaultResult.success(new AppletsLoginReturnModel().setToken(token));
    }


    @Data
    static class AppletsLoginModel {
        @ApiModelProperty(value = "小程序应用ID")
        private String appid;
        @ApiModelProperty(value = "小程序登录时获取的 code")
        private String jsCode;
    }

    @Data
    static class AppletsLoginReturnModel {
        @ApiModelProperty(value = "登录token")
        private String token;

    }
}
